#!/usr/bin/env python3
"""
初始化测试数据
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))

from app.core.database import SessionLocal
from app.models.product import ProductCategory
from app.schemas.product import ProductCreate
from app.services.product_service import ProductService

def init_test_category():
    """初始化测试分类"""
    db = SessionLocal()
    try:
        # 检查是否已存在测试分类
        existing_category = db.query(ProductCategory).filter(ProductCategory.name == "测试分类").first()
        if existing_category:
            print(f"测试分类已存在，ID: {existing_category.id}")
            return existing_category.id

        # 创建测试分类
        category = ProductCategory(
            name="测试分类",
            description="用于API测试的分类",
            sort_order=1,
            is_active=1
        )
        db.add(category)
        db.commit()
        db.refresh(category)

        print(f"测试分类创建成功，ID: {category.id}")
        return category.id

    except Exception as e:
        print(f"创建测试分类失败: {e}")
        db.rollback()
        return None
    finally:
        db.close()

def create_test_product():
    """创建测试商品"""
    db = SessionLocal()
    try:
        # 先获取分类ID
        category = db.query(ProductCategory).filter(ProductCategory.name == "测试分类").first()
        if not category:
            print("测试分类不存在，请先运行 init_test_category()")
            return

        # 检查是否已存在测试商品
        from app.models.product import Product
        existing_product = db.query(Product).filter(Product.sku == "TEST001").first()
        if existing_product:
            print(f"测试商品已存在，ID: {existing_product.id}")
            return existing_product.id

        # 创建测试商品
        product_data = ProductCreate(
            name="测试商品",
            description="这是一个用于API测试的商品",
            price="99.99",
            original_price="129.99",
            stock=100,
            category_id=category.id,
            sku="TEST001",
            is_active=True,
            is_featured=False
        )

        product = ProductService.create_product(db, product_data)
        print(f"测试商品创建成功，ID: {product.id}")
        return product.id

    except Exception as e:
        print(f"创建测试商品失败: {e}")
        return None
    finally:
        db.close()

if __name__ == "__main__":
    print("初始化测试数据...")
    category_id = init_test_category()
    if category_id:
        product_id = create_test_product()

    print("测试数据初始化完成!")